// @flow
import React, { Component } from 'react'
import styles from './JobList.css'
import { notification } from 'antd'
import JobListGrid from './JobListGrid'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import moment from 'moment'

type Props = {
  history: Object
}
type States = {
  jobs: Array<Object>
}
class JobList extends Component {
  props: Props
  state: States
  getJobs: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      jobs: []
    }
    this.getJobs = this.getJobs.bind(this)
  }

  componentDidMount () {
    this.getJobs()
  }

  getJobs () {
    const taskState = this.props.history.location.state
    let modelId = ''
    if (taskState != null) {
      modelId = taskState.taskData.modelIdCopy
    }
    let jobUrl = `${__SERVICE_API__}analysis/jobs?pageNum=1&pageSize=20`
    if (modelId !== '') {
      jobUrl = `${__SERVICE_API__}analysis/jobs??pageNum=1&pageSize=20&modelId=` + modelId
    }
    //
    universalFetch(jobUrl)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          notification.error({
            message: '提醒',
            description: json.message,
            placement: 'topRight',
            top: 63
          })
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          jobs: json.result.map((d, index) => {
            d['key'] = index + 1
            if (d.startTime === null) {
              d['startTime'] = ''
            } else {
              d['startTime'] = moment.utc(d.startTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            }
            if (d.endTime === null) {
              d['endTime'] = ''
            } else {
              d['endTime'] = moment.utc(d.endTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            }
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    const { jobs } = this.state
    const { history } = this.props
    return (
      <div className={styles['main']}>
        <JobListGrid {...{
          history,
          refreshJobList: this.getJobs,
          rowData: jobs
        }} />
      </div>
    )
  }
}

export default JobList
